import { defineStore } from 'pinia';
// import { useUiStore } from './uiStore'; // Potentially for error handling

export const useTagStore = defineStore('tag', {
  state: () => ({
    globalTags: [], // string[]
    activeFilterTags: [], // string[] - tags shown as checkboxes in UI F
    selectedFilterTags: [], // string[] - tags currently selected by user for filtering
  }),
  actions: {
    setGlobalTags(tags) {
      this.globalTags = tags || [];
    },
    setActiveFilterTags(tags) {
      this.activeFilterTags = tags || [];
      // When active filter tags change, selected tags should also be updated.
      // Default behavior: select all active tags.
      this.selectedFilterTags = [...this.activeFilterTags];
    },
    setSelectedFilterTags(tags) {
      this.selectedFilterTags = tags || [];
    },
    updateSelectedFilterTag(tag, isSelected) {
      if (isSelected) {
        if (!this.selectedFilterTags.includes(tag)) {
          this.selectedFilterTags.push(tag);
        }
      } else {
        this.selectedFilterTags = this.selectedFilterTags.filter(t => t !== tag);
      }
    },
    resetFilters() {
      // Resets selected tags to be all currently active tags
      this.selectedFilterTags = [...this.activeFilterTags];
    },
    async refreshActiveFilterTags() {
      // const uiStore = useUiStore();
      // uiStore.setAppError(null);
      try {
        const response = await window.pywebview.api.get_active_tags_for_filter();
        if (response.success && response.data) {
          this.setActiveFilterTags(response.data.active_tags); // This will also reset selectedFilterTags
        } else {
          console.error('Failed to refresh active filter tags:', response.error_message);
          // uiStore.setAppError(response.error_message || 'Failed to refresh active filter tags.');
        }
      } catch (error) {
        console.error('Error refreshing active filter tags:', error);
        // uiStore.setAppError(`Error refreshing active filter tags: ${error.message || 'Unknown error'}`);
      }
    },
    async refreshGlobalTags() {
      // const uiStore = useUiStore();
      // uiStore.setAppError(null);
      try {
        const response = await window.pywebview.api.get_global_tags();
        if (response.success && response.data) {
          this.setGlobalTags(response.data.global_tags);
        } else {
          console.error('Failed to refresh global tags:', response.error_message);
          // uiStore.setAppError(response.error_message || 'Failed to refresh global tags.');
        }
      } catch (error) {
        console.error('Error refreshing global tags:', error);
        // uiStore.setAppError(`Error refreshing global tags: ${error.message || 'Unknown error'}`);
      }
    },
    // Initial tag data fetching is handled in App.vue
    // and then setGlobalTags and setActiveFilterTags are called.
  },
});